/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package net.thick4.context;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.thick4.convention.Convention;
import net.thick4.deploy.DeploymentMode;

import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 開発モードの場合に Spring のコンテキストの再読み込みを実行するServletFilterです。
 * なお、このフィルターは現在のスレッドのクラスローダーを変更するため、
 * このフィルターを通った後は ContextLoader#getCurrentContext() がnullを返すようになります。
 * このフィルターを利用して、かつ、ApplicationContext を取得したい場合は、
 * WebApplicationContextUtils#getWebApplicationContext(ServletContext) を利用してください。
 */
public class ReloadContextFilter extends OncePerRequestFilter {

	/**
	 * 開発モードの場合にSpringのコンテキストの再読み込みを実行します。 
	 * @param request 処理中のHttpServletRequest
	 * @param response 処理中のHttpServletResponse
	 * @param filterChain 処理中のFilterChain
	 */
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    	if (DeploymentMode.isDevelopmentMode()) {
			logger.info("Reloading WebApplicationContext started");
			
			XmlWebApplicationContext webContext = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(getServletContext());
			Convention convention = (Convention) BeanFactoryUtils.beanOfType(webContext, Convention.class);
			
			ClassLoader original = Thread.currentThread().getContextClassLoader();
			ReloadableClassLoader reloadableClassLoader = new ReloadableClassLoader(original, convention);

			ClassUtils.overrideThreadContextClassLoader(reloadableClassLoader);
			webContext.setClassLoader(reloadableClassLoader);
			webContext.getBeanFactory().setBeanClassLoader(reloadableClassLoader);
			try {
				ReloadableUtil.reload();
				logger.info("Reloading WebApplicationContext completed");
				filterChain.doFilter(request, response);
			} finally {
				reloadableClassLoader.dispose();
				ClassUtils.overrideThreadContextClassLoader(original);
			}
		} else {
			filterChain.doFilter(request, response);
		}
	}
	
}
